package Server;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.util.*;

/**
 * Server
 * Mediator, Observer
 * @author Yaxing Chen
 *
 */
public class Server {
	
	//singleton & bridge & mediator
	//private ClientList list;
	
	//singleton & bridge
	private static ClientMediator clientMediator;
	
	/**
	 * get client mediator
	 * @return ClientMediator clientMediator
	 */
	public static ClientMediator getMediator(){
		if(clientMediator == null){
			clientMediator = new ClientMediator();
		}
		return clientMediator;
	}
    
    private void startServer(){
    	JFrame jf = new JFrame("Chatter Server");
        JTextField field = new JTextField(30);
        JTextArea area = new JTextArea();
        Cursor cursor = new Cursor(Cursor.TEXT_CURSOR);
        field.requestFocusInWindow();
        area.setEditable(false);
        area.setFont(new Font("Times New Roman",0,14));
        JButton clear = new JButton("Clear");
        JButton button = new JButton("Send");
        Panel panel = new Panel();
        //panel.add(field);
        //panel.add(button);
        //panel.add(clear);
        jf.add(area,"Center");
        jf.add(panel,"South");
        Toolkit toolkit = jf.getToolkit();
        Dimension d = toolkit.getScreenSize();
        jf.setBounds(d.width/2-268,d.height/2-163,536,327);
        jf.setResizable(false);
        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.validate();
        
        try{
        	
            ServerSocket ss = new ServerSocket(2008);
            while(true){
	            Socket s = ss.accept();
	            InputStream is = s.getInputStream();
	            OutputStream os = s.getOutputStream();
	            DataInputStream dis = new DataInputStream(is);
	            DataOutputStream dos = new DataOutputStream(os);
	            //SSay say = new SSay(dos,field,button,area,clear);
	            
	            //assign client id to new client
	            int newUserId = Server.getMediator().getNewUserId();
	            Server.getMediator().newClient(new ClientSocket(s, dis, dos, newUserId));
	            
	            ServerReceiver receiver = new ServerReceiver(dis, area, 0, newUserId);     
	            //jf.addFocusListener(say);
	            receiver.start();
	            
	            //add client to client list
	            
	            
        	}
        }catch(IOException e){
            e.printStackTrace();
        }
    }
    
    public static void main(String args[]){
        Server server = new Server();
        server.startServer();
    }
}





